<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-input
            v-model="searchForm.keyword"
            clearable
            placeholder="搜索用户名、昵称、邮箱或手机号"
            style="width: 300px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <el-select
            v-model="searchForm.status"
            clearable
            placeholder="用户状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="正常"/>
          <el-option :value="0" label="禁用"/>
        </el-select>

        <el-select
            v-model="searchForm.gender"
            clearable
            placeholder="性别"
            style="width: 100px"
            @change="handleSearch"
        >
          <el-option :value="1" label="男"/>
          <el-option :value="2" label="女"/>
          <el-option :value="0" label="未知"/>
        </el-select>

        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </div>

      <div class="table-toolbar-right">
        <el-button type="primary" @click="handleRefresh">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table
          v-loading="loading"
          :data="users"
          stripe
          style="width: 100%"
      >
        <el-table-column label="ID" prop="id" width="80"/>

        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar">
              <el-icon>
                <User/>
              </el-icon>
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column label="用户名" prop="username" width="120"/>

        <el-table-column label="昵称" prop="nickname" width="120">
          <template #default="{ row }">
            {{ row.nickname || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="邮箱" prop="email" width="180">
          <template #default="{ row }">
            {{ row.email || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="手机号" prop="phone" width="130">
          <template #default="{ row }">
            {{ row.phone || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="getGenderTagType(row.gender)" size="small">
              {{ getGenderText(row.gender) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="最后登录" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.lastLoginTime) || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="注册时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleViewDetail(row)"
              >
                查看
              </el-button>

              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleUpdateStatus(row, 0)"
              >
                禁用
              </el-button>

              <el-button
                  v-else
                  size="small"
                  type="success"
                  @click="handleUpdateStatus(row, 1)"
              >
                启用
              </el-button>

              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <UserDetailDialog
        v-model="detailDialogVisible"
        :user-id="selectedUserId"
        @refresh="handleRefresh"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Refresh, Search, User} from '@element-plus/icons-vue'
import {useUserStore} from '@/store/user'
import {formatDateTime} from '@/utils'
import UserDetailDialog from './components/UserDetailDialog.vue'

// 用户Store
const userStore = useUserStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  status: null,
  gender: null
})

const detailDialogVisible = ref(false)
const selectedUserId = ref(null)

// 计算属性
const users = computed(() => userStore.users)
const loading = computed(() => userStore.loading)
const total = computed(() => userStore.total)
const currentPage = computed({
  get: () => userStore.currentPage,
  set: (value) => userStore.setPagination(value, userStore.pageSize)
})
const pageSize = computed({
  get: () => userStore.pageSize,
  set: (value) => userStore.setPagination(userStore.currentPage, value)
})

// 方法
const handleSearch = () => {
  userStore.setPagination(1, pageSize.value)
  loadUserList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: null,
    gender: null
  })
  handleSearch()
}

const handleRefresh = () => {
  loadUserList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadUserList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadUserList()
}

const handleViewDetail = (user) => {
  selectedUserId.value = user.id
  detailDialogVisible.value = true
}

const handleUpdateStatus = async (user, status) => {
  try {
    const action = status === 1 ? '启用' : '禁用'
    await ElMessageBox.confirm(
        `确定要${action}用户 "${user.username}" 吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await userStore.updateUserStatus(user.id, status)
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除用户 "${user.username}" 吗？此操作不可恢复！`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
    )

    await userStore.deleteUser(user.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const loadUserList = async () => {
  try {
    await userStore.getUserList(searchForm)
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载失败，请重试')
  }
}

const getGenderText = (gender) => {
  const map = {0: '未知', 1: '男', 2: '女'}
  return map[gender] || '未知'
}

const getGenderTagType = (gender) => {
  const map = {0: 'info', 1: 'primary', 2: 'success'}
  return map[gender] || 'info'
}

// 生命周期
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.page-container {
  padding: var(--admin-space-lg);
  background: var(--admin-bg-layout);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: var(--admin-space-lg);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  color: var(--admin-text-primary);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.table-container {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: var(--admin-space-lg);
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
}

.table-toolbar-left {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.table-toolbar-right {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  padding: var(--admin-space-lg);
  text-align: center;
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
}

/* 用户头像样式 */
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.user-avatar:hover {
  border-color: var(--admin-primary);
  box-shadow: var(--admin-shadow-sm);
}

/* 状态标签样式 */
.status-tag {
  font-size: var(--admin-font-xs);
  padding: var(--admin-space-xs) var(--admin-space-sm);
  border-radius: var(--admin-radius-sm);
  font-weight: var(--admin-font-medium);
  display: inline-flex;
  align-items: center;
  line-height: 1;
}

.status-active {
  background: var(--admin-success-bg);
  color: var(--admin-success);
  border: 1px solid var(--admin-success-light);
}

.status-inactive {
  background: var(--admin-error-bg);
  color: var(--admin-error);
  border: 1px solid var(--admin-error-light);
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: var(--admin-space-xs);
  align-items: center;
}

.action-buttons .el-button {
  padding: var(--admin-space-xs) var(--admin-space-sm);
  font-size: var(--admin-font-xs);
  height: var(--admin-height-sm);
  border-radius: var(--admin-radius-sm);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: var(--admin-space-md);
    align-items: flex-start;
  }

  .table-toolbar {
    flex-direction: column;
    gap: var(--admin-space-sm);
    align-items: stretch;
  }

  .table-toolbar-left,
  .table-toolbar-right {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
